<template>
  <div>
    <el-dialog   v-model="store.openUpload">
      <el-upload
          ref="uploadRef"
          class="upload"
          :limit="1"
          drag
          :format="['xls','xlsx']"
          accept=".xls, .xlsx"
          action="#"
          :file-list="fileList"
          :http-request="handleUpload"
          :auto-upload="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或  <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            仅允许导入xls、xlsx格式文件。 <em @click="downloadTemplate()">下载模板</em>
          </div>
          <div class="button-group">
            <el-button type="primary" class="el-button__primary" @click="submitUpload">
              确认
            </el-button>
            <el-button @click="closeUpload">
              取消
            </el-button>
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import {roleStore} from "@/stores/role/roleStore";
import {defineEmits, ref} from "vue";
import {streamDownLoad} from "@/utils/download.ts";
import {ElMessage, type UploadInstance} from "element-plus";
import {importRole} from "@/api/role";
import {questionStore} from "@/stores/question/questionStore.ts";
import {importQuestion} from "@/api/question/question.ts";
const store=questionStore()
const emit = defineEmits(['refresh'])
const uploadRef = ref<UploadInstance>()
const fileList = ref([]);
/**
 * 下载模板
 */
const  downloadTemplate=async () => {
  const fileName = "template/question_Import.xlsx"
  await streamDownLoad(fileName)
}

/**
 * 关闭页面
 */
const closeUpload=()=>{
   store.setQuestionUploadOpen(false)
   uploadRef.value?.clearFiles()
  //刷新数据
   emit('refresh')
}

const submitUpload=()=>{
  uploadRef.value?.submit()
}

/**
 * 自定义导入
 */
const handleUpload=async (fileObject) => {
  const  formData= new FormData()
  formData.append("file",fileObject.file)
  try {
    store.setQuestionUploadOpen(false)
    const res = await importQuestion(store.bankId,formData)
    ElMessage.success("导入成功")
    closeUpload()
  }catch (e) {
    closeUpload()
  }
}
</script>

<style scoped>
em{
  color:rgb(46, 92, 246)!important;
  cursor: pointer;
}
:deep(.el-upload-dragger:hover) {
  --el-color-primary:rgb(46, 92, 246);
  border-color: var(--el-color-primary);
}
.el-upload__tip{
  text-align: center;
 }
.button-group{
  display: flex;
  justify-content: right;
  margin-top: 10px;
  .el-button{
    width: 80px;
  }
}
</style>